package com.xjy.web.controller.controller;

import cn.hutool.core.util.StrUtil;
import com.xjy.common.annotation.Log;
import com.xjy.common.constant.UserConstants;
import com.xjy.common.core.controller.BaseController;
import com.xjy.common.core.domain.AjaxResult;
import com.xjy.common.core.domain.entity.SysBudget;
import com.xjy.common.enums.BusinessType;
import com.xjy.common.exception.UtilException;
import com.xjy.common.utils.SecurityUtils;
import com.xjy.system.domain.SysBudgetExtend;
import com.xjy.system.domain.bo.SysBudgetStatisticsQueryBo;
import com.xjy.system.domain.vo.SysBudgetStatisticsVo;
import com.xjy.system.service.ISysBudgetService;
import com.xjy.system.service.ISysBudgetStatisticsService;
import com.xjy.system.utils.BeanMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;


/**
 * 预算汇总Controller
 *
 * @date 2022-04-27
 */
@Api(value = "预算科目信息汇总", tags = {"预算科目信息汇总"})
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@RestController
@RequestMapping("/system/budget_statistics_new")
public class SysBudgetStatisticsNewController extends BaseController {
	@Autowired
	private ISysBudgetService iSysBudgetService;
	@Autowired
	private ISysBudgetStatisticsService iSysBudgetStatisticsService;


	@ApiOperation("查询预算科目信息列表")
	@PreAuthorize("@ss.hasPermi('system:budget_statistics_new:list')")
	@GetMapping("/list")
	public AjaxResult list(SysBudget sysBudget){
		List<SysBudget> baseList = iSysBudgetService.selectBudgetList(sysBudget);

		SysBudgetStatisticsQueryBo bo = new SysBudgetStatisticsQueryBo();
		bo.setProjId(sysBudget.getProjId());
		bo.setAttribute(sysBudget.getSubType());
		List<SysBudgetStatisticsVo> summaryList = iSysBudgetStatisticsService.queryList(bo);

/*		List<SysBudgetExtend> newList = baseList.stream().map(e->{
			SysBudgetExtend sbe = BeanMapper.map(e, SysBudgetExtend.class);
			Optional<SysBudgetStatisticsVo> optional= summaryList.stream().filter(i->i.getBudgetId().equals(e.getId())).findFirst();
			if (optional.isPresent()) {
				sbe.setAmt(optional.get().getAmount());
			} else {
				sbe.setAmt(BigDecimal.ZERO);
			}
			return sbe;
		}).collect(Collectors.toList());*/
		List<SysBudgetExtend> newList = summaryList.stream().map(e->{
			SysBudgetExtend sbe = null;
			Optional<SysBudget> optional= baseList.stream().filter(i->i.getId().equals(e.getBudgetId())).findFirst();
			if (optional.isPresent()) {
				sbe = BeanMapper.map(optional.get(), SysBudgetExtend.class);
				sbe.setAmt(e.getAmount());
				sbe.setProjName(e.getProjName());
			}
			return sbe;
		}).collect(Collectors.toList());
		return AjaxResult.success(newList);
	}

	/**
	 * 获取预算科目信息详细信息
	 */
	@ApiOperation("获取预算科目信息详细信息")
	@PreAuthorize("@ss.hasPermi('system:budget_statistics_new:query')")
	@GetMapping("/{id}")
	public AjaxResult getinfo(@PathVariable Long id ) {
		return AjaxResult.success(iSysBudgetService.getByIdInfo(id));
	}
	/**
	 * 查询科目列表（排除节点）
	 */
	@ApiOperation("查询科目列表（排除节点）")
	@PreAuthorize("@ss.hasPermi('system:budget_statistics_new:list')")
	@GetMapping("/list/exclude/{id}")
	public AjaxResult excludeChild(@PathVariable(value = "id", required = false) Long id) {
		List<SysBudget> list = iSysBudgetService.selectBudgetList( new SysBudget());
		Iterator<SysBudget> it = list.iterator();
		while (it.hasNext())
		{
			SysBudget d = (SysBudget) it.next();
			if (d.getId().intValue() == id
				|| ArrayUtils.contains(StrUtil.splitToArray(d.getAncestors(), ","), id + ""))
			{
				it.remove();
			}
		}
		return AjaxResult.success(list);
	}
   /**
	* 获取科目预算下拉数列表
	* */
   @GetMapping("/treeselect")
   public AjaxResult treeselect(SysBudget sysBudget) {
	   sysBudget.setAuditStatus(true);
	   sysBudget.setStatus("0");
	   List<SysBudget> list = iSysBudgetService.selectBudgetList(sysBudget);
	   return AjaxResult.success(iSysBudgetService.treeselectList(list));
   }
  /**
   * 新增预算科目
   * */
	@ApiOperation("新增预算科目信息")
	@PreAuthorize("@ss.hasPermi('system:budget_statistics_new:add')")
	@Log(title = "预算科目信息", businessType = BusinessType.INSERT)
	@PostMapping
	public AjaxResult add(@RequestBody SysBudget sysBudget) {
		if (UserConstants.NOT_UNIQUE.equals(iSysBudgetService.checkDeptNameUnique(sysBudget)))
		{
			return AjaxResult.error("新增科目'" + sysBudget.getSubjectName() + "'失败，科目名称已存在");
		}
		sysBudget.setCreateBy(SecurityUtils.getUsername());
		return toAjax(iSysBudgetService.insertBudget(sysBudget));
	}

	/**
	 * 加载对应角色科目树
	 */
	@GetMapping(value = "/roleBudgetTreeselect/{roleId}")
	public AjaxResult roleBudgetTreeselect(@PathVariable("roleId") Long roleId)
	{
		List<SysBudget> depts = iSysBudgetService.selectBudgetList(new SysBudget());
		Map<String,Object> ajax = new HashMap<>();
		ajax.put("checkedKeys", iSysBudgetService.selectBudgetListByRoleId(roleId));
		ajax.put("depts", iSysBudgetService.buildBudgetTreeSelect(depts));
		return AjaxResult.success(ajax);
	}
	}

